from django.shortcuts import render
from django.http import JsonResponse
from django.views import View
from home.models import Area
from django.core.cache import cache
# Create your views here.


# /api/v1.0/areas
class CityAreasView(View):
    def get(self, request):
        """获取所有城区信息"""
        cache_data = cache.get('city')
        if not cache_data:
            # 没有缓存数据，进行数据库的查询
            try:
                city = Area.objects.filter().values('id', 'name')
                city = list(city)
                data = []
                for a_dict in city:

                    d_id = a_dict['id']
                    d_name = a_dict['name']
                    d_dict = {
                        "aid": d_id,
                        "aname": d_name
                    }
                    data.append(d_dict)

                cache.set('data', data, 3600)

            except Exception as e:
                return JsonResponse({
                    'errmsg': '城区信息获取错误',
                    'errno': 400,
                })
        else:
            # 直接使用缓存中获取的数据
            data = cache_data
        return JsonResponse({
            "errmsg": "获取成功",
            "errno": "0",
            "data": data
        })




